<?php
// +----------------------------------------------------------------------
// | Description: 商品属性管理
// +----------------------------------------------------------------------
// | Author: orchief
// +----------------------------------------------------------------------
// | Date: 2018-01-24 16:43:34
// +----------------------------------------------------------------------

namespace app\client\controller;

use app\common\controller\Rest;
use think\Db;

class ProductAttrs extends Rest
{
    public $modelName = 'ProductAttr';
    public function _initialize()
    {
        parent::_initialize();
        // $this -> abort(!$this -> isClient, 'Permission denied', 403);
    }

    public function OriginIndex()
    {
        $data = self::$model->getDataList();
        $this->jsonData($data, self::$model->getError());
    }

    public function index()
    {
        $data = self::$model->getDataList();
        $filterData = $data['list'];
        $AttributeId = [];
        foreach ($filterData as $k => $v) {
            if (in_array($v['AttributeId'], $AttributeId)) {
                $key = array_search($v['AttributeId'], $AttributeId);
                $list[$key]['AttributeList'][] = [
                    'ValueId' => $v['ValueId'],
                    'ValueStr' => $v['ValueStr'],
                    'IsImg' => $v['IsImg'],
                ];
            } else {
                $AttributeId[] = $v['AttributeId'];
                $temp = [];
                $temp['ProductId'] = $v['ProductId'];
                $temp['AttributeId'] = $v['AttributeId'];
                $temp['AttributeName'] = $v['AttributeName'];
                $temp['Id'] = $v['Id'];
                $temp['SortBy'] = $v['SortBy'];
                $temp['IsSku'] = $v['IsSku'];
                $temp['AttributeList'][] = [
                    'ValueId' => $v['ValueId'],
                    'ValueStr' => $v['ValueStr'],
                    'IsImg' => $v['IsImg'],
                ];
                $list[] = $temp;
            }
        }
        $data['list'] = $list;
        $this->jsonData($data, self::$model->getError());
    }

    /**
     * Cartesian product that generates attribute values and attributes
     *
     * @return void
     */
    public function genSku()
    {
        // TODO: process Cartesian product
        $params = $this->param;

        if ($params['IsSku'] == 1) {
            self::$model->startTrans();
            try {
                // attributes
                $attributes = Db::table('shop_goods_attributes');
                $attributes->insert(['AttributeName' => $params['AttributeName']]);
                $ProductAttrs['AttributeId'] = $attributes->getLastInsId();
                $ProductAttrs['ProductId'] = $params['ProductId'];
                $ProductAttrs['IsSku'] = 1;
                // attribute_values
                foreach ($params['AttributeValueArray'] as $k => $v) {
                    $attribute_values = Db::table('shop_goods_attribute_values');
                    $attribute_values->insert(['AttributeId' => $ProductAttrs['AttributeId'], 'ValueStr' => $v]);
                    $ProductAttrs['ValueId'] = $attribute_values->getLastInsId();
                    $res = self::$model->insert($ProductAttrs);
                }

                self::$model->commit();
            } catch (\Exception $e) {
                self::$model->rollback();
                $this->abort(false, $e->getMessage());
            }

            self::$model->startTrans();
            try {
                $this->genDkaer($params['ProductId']);

                self::$model->commit();
            } catch (\Exception $e) {
                self::$model->rollback();
                $this->abort(false, $e->getMessage());
            }

            $this->checkRes($res, '添加成功', self::$model->getError());

        } else {
            self::$model->startTrans();
            try {
                // attributes
                $attributes = Db::table('shop_goods_attributes');
                $attributes->insert(['AttributeName' => $params['AttributeName']]);
                $params['AttributeId'] = $attributes->getLastInsId();

                // attribute_values
                $attribute_values = Db::table('shop_goods_attribute_values');
                $attribute_values->insert(['AttributeId' => $params['AttributeId'], 'ValueStr' => $params['AttributeValueArray'][0]]);
                $params['ValueId'] = $attribute_values->getLastInsId();

                $res = self::$model->createData($params);

                self::$model->commit();
            } catch (\Exception $e) {
                self::$model->rollback();
                $this->abort(false, $e->getMessage());
            }
            $this->checkRes($res, '添加成功', self::$model->getError());
        }

        // TODO: insert data to mysql
    }

    /**
     * 删除旧的记录
     */
    public function deleteSku($ProductId)
    {
        // 查询是否已经产生订单
        $res = Db::table('shop_orders_items')->where(['ProductId' => $ProductId])->count();
        $this->abort(!$res, '删除失败! (该规格已经生成订单 不可重构)');
        // 删除之前生成的所有规格信息
        $SkuInfo = Db::table('shop_goods_sku')->where(['ProductId' => $ProductId])->select();
        $res1 = Db::table('shop_goods_sku')->where(['ProductId' => $ProductId])->delete();
        foreach ($SkuInfo as $k => $v) {
            $SkuIds[] = $v['Id'];
        }

        $res2 = Db::table('shop_goods_sku_items')->where('SkuId', 'in', $SkuIds)->delete();
        return $res1 && $res2;
    }

    /**
     * 重置并生成新的笛卡尔积
     */
    public function genDkaer($ProductId)
    {
        // 删除旧的记录
        $res = $this -> deleteSku($ProductId);
        // 生成规格值组成的数组
        $products = Db::table('shop_goods_product_attributes')->where('ProductId', $ProductId)->where(['IsSku' => 1])->select();
        foreach ($products as $k => $v) {
            $arr[$v['AttributeId']][] = $v['ValueId'];
        }
        foreach ($arr as $k => $v) {
            $resArr[] = $v;
        }

        // 生成笛卡尔积
        $res = $this->combineDika($resArr);

        // 对笛卡尔积进行处理 生成需要插入的数据
        foreach ($res as $k => $v) {
            // 获取skuId
            $shop_goods_sku = Db::table('shop_goods_sku');
            $shop_goods_sku->insert(['ProductId' => $ProductId]);
            $SkuId = $shop_goods_sku->getLastInsId();
            $BaseInfo = '';
            // p($SkuId);
            // 为当前的skuid生成记录
            foreach ($v as $kk => $vv) {
                $AttributeInfo = Db::table('shop_goods_attribute_values')->where(['Id' => $vv])->find();
                $AttributeId = $AttributeInfo['AttributeId'];
                $insertData['SkuId'] = $SkuId;
                $insertData['AttributeId'] = $AttributeId;
                $insertData['ValueId'] = $vv;
                $res = Db::table('shop_goods_sku_items')->insert($insertData);
                // 生成基本信息
                $AttributeName = Db::table('shop_goods_attributes')->where(['Id' => $AttributeId])->find()['AttributeName'];
                $BaseInfo .= $AttributeName . ": " . $AttributeInfo['ValueStr'] . "  ";
            }

            // 将生成的基本信息更新
            Db::table('shop_goods_sku')->where(['Id' => $SkuId])->update(['Content' => $BaseInfo]);
        }
    }

    /**
     * 删除规格的时候会重置
     */
    public function delete()
    {
        $res = self::$model->delDataById($this->param['id']);

        // 通过规格id 查到 商品id
        $ProductInfo = Db::table('shop_goods_product_attributes')->where(['Id' => $this->param['id']])->where(['IsSku' => 1])->find();
        if($ProductInfo){
            $this->genDkaer($ProductInfo['ProductId']);
        }

        $this->checkRes($res, '删除成功', self::$model->getError());
    }

    /**
     * 所有数组的笛卡尔积
     *
     * @param unknown_type $data
     */
    private function combineDika($data)
    {
        $cnt = count($data);
        $result = array();
        foreach ($data[0] as $item) {
            $result[] = array($item);
        }
        for ($i = 1; $i < $cnt; $i++) {
            $result = $this->combineArray($result, $data[$i]);
        }
        return $result;
    }

    /**
     * 两个数组的笛卡尔积
     *
     * @param unknown_type $arr1
     * @param unknown_type $arr2
     */
    private function combineArray($arr1, $arr2)
    {
        $result = array();
        foreach ($arr1 as $item1) {
            foreach ($arr2 as $item2) {
                $temp = $item1;
                $temp[] = $item2;
                $result[] = $temp;
            }
        }
        return $result;
    }
}
